package me.hunche.app.sms;

import java.util.Date;
import java.util.List;

import me.hunche.app.dao.ActivityDao;
import me.hunche.app.dao.ActivityMemberDao;
import me.hunche.app.dao.UserDao;
import me.hunche.app.domain.Activity;
import me.hunche.app.domain.ActivityMember;
import me.hunche.app.domain.User;
import me.hunche.app.service.CoreService;
import me.hunche.app.service.NotifyService;
import me.hunche.app.service.SMSService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hp.hpl.helper.misc.DateHelper;

@Service("OKHandler")
public class OKHandler implements SMSHandler,InitializingBean{
	
	private static final String prefix ="OK";
	private static final Logger logger = Logger.getLogger(OKHandler.class);
	
	@Autowired ActivityDao activityDao;
	@Autowired ActivityMemberDao activityMemberDao; 
	@Autowired CoreService coreService;
	@Autowired UserDao userDao;
//	@Autowired NotifyService notifyService;
	

	@Autowired SMSService smsService;

	public String getPrefix() {
		return prefix;
	}
	
	public void afterPropertiesSet() throws Exception {
		
		logger.info("initialize");
		smsService.registerHandler(this);
	}

	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public boolean execute(String mobile, String content) {
		if(logger.isDebugEnabled()){
			logger.debug("execute("+mobile +" "+ content+ ") - start");
		}
		
		
		Date tomorrow = DateHelper.dayStart(DateHelper.now(),1);//1
		User user  = userDao.findByMobile(mobile);
		List<Activity> as = activityDao.findByStatusAndTeamIdAndActivityDate(Activity.STATUS_READY2,user.getTeamId(),tomorrow);
		if(as!=null && !as.isEmpty()){
			ActivityMember am = activityMemberDao.findByActivityIdAndUserId(as.get(0).getId(),user.getId());
			if(!am.hasReady()){
//				am.setReadyFlag(ActivityMember.FLAG_TRUE);
				am.setReadyTime(DateHelper.now());
				activityMemberDao.update(am);
			}
		}else{
			logger.error("no ready activity");
		}
		
		if(logger.isInfoEnabled()){
			logger.info("execute("+mobile +" "+ content+ " - end");
		}
		return true;
	}
}
